﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace QuickSearchAndSelect
{
    /// <summary>
    /// Interaction logic for SearchAndSelectView.xaml
    /// </summary>
    public partial class SearchAndSelectView : UserControl
    {
        public SearchAndSelectViewModel ViewModel { get; set; }
        public SearchAndSelectView()
        {
            InitializeComponent();
            ViewModel = new SearchAndSelectViewModel();
            ViewModel.PropertyChanged += new PropertyChangedEventHandler(ViewModel_PropertyChanged);
            DataContext = ViewModel;
        }

        internal event EventHandler<KeyEventArgs> ListBoxKeyDown;

        protected void OnListBoxPreviewKeyDown(object sender, KeyEventArgs e)
        {
            ListBoxKeyDown(sender, e);
        }

        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "SelectedIndex":
                case "SelectedItem":
                    if (ViewModel.SelectedItem != null)
                    {
                        Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
                            new Action(() =>
                            {
                                var i = Products.ItemContainerGenerator.ContainerFromItem(ViewModel.SelectedItem) as ListBoxItem;
                                // select and keyboard-focus the second item 
                                i.IsSelected = true; 
                            }));
                        Products.ScrollIntoView(ViewModel.SelectedItem);
                    }
                    break;
            }
        }
    }
}
